import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';
import 'package:ls_work/message/message_config.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/net/response/response_data.dart';
import 'package:ls_work/net/response/service_order_ddetail_data.dart';
import 'package:ls_work/viewmodel/model/combo_data_model.dart';
import 'package:ls_work/widgets/add_image_widget.dart';

import '../../a_elder/models/code_value_entity.dart';
import '../../util/location_utils.dart';

class StartServiceOrderViewModel extends BaseViewModel {
  final ServiceOrderDdetailData detail;

  StartServiceOrderViewModel(BuildContext context, this.detail)
      : super(context) {
    siteName = detail.site ?? "";
  }

  String siteName = "";
  static const List<String> format = [
    yyyy,
    "-",
    mm,
    '-',
    dd,
    " ",
    HH,
    ":",
    nn,
    ":",
    ss
  ];
  var startTime = DateTime.now().toDateStr(format);
  List<String> files = [];

  var comboModel = ComboDataModel();

  List<CodeValue> siteList = [];

  var locationAddress = "";
  double? longitude;
  double? latitude;

  var locationCount = 0;

  void chooseSite() {
    var current = siteList.firstWhere((element) => element.nameCn == siteName,
        orElse: () => siteList.first);
    DataPickerView(context, siteList, currentFirstData: current,
        onSubmitListener: (p1, p2, p3) {
      siteName = siteList[p1].nameCn ?? "";
      notifyListeners();
    }).show();
  }

  Future<void> requestSiteCombo() async {
    try {
      siteList = await comboModel.getComboData("556670");
    } catch (e) {
      showToast(NetErrorUtils.getNetError(e));
    }
  }

  void selectTime() {
    DatePicker.showDateTimePicker(context, onConfirm: (date) {
      startTime = date?.toDateStr(format) ?? "";
      notifyListeners();
    });
  }

  Future<void> startClick() async {
    // if(files.isEmpty){
    //   showToast("请选择照片");
    //   return;
    // }

    if(longitude==null){
      showToast("请先等待定位完成");
      return;
    }

    showLoadingDialog();
    try {
      var uploadFiles = await _uploadFiles();
      var result = await PostRequest.startService(
          detail.id.toString(), startTime, uploadFiles,
          site: siteName,
          serveAddress: locationAddress,
          longitude: longitude,
          latitude: longitude);
      hideDialog();
      var bean = ResponseBean.fromJson(result);
      if ("0" == bean.code) {
        showToast('已开始服务');
        sendMessage(SendMessageEvent(MessageConfig.REFRESH_ORDER));
        finish();
      } else {
        showToast(bean.msg ?? "");
      }

    } catch (e) {
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));

    }
  }

  ///上传文件
  Future<List<Map<String, dynamic>>> _uploadFiles() async {
    List<Map<String, dynamic>> result = [];
    for (var file in files) {
      var data = await PostRequest.uploadFile(file);
      var bean = ResponseBean.fromJson(data);
      if ('0' == bean.code) {
        result.add(bean.data);
      } else {
        throw bean.msg ?? "";
      }
    }
    return result;
  }

  Widget addImageWidget() {
    return AddImageWidget(
      (file) {
        this.files = file;
      },
      files: this.files,
      cameramsg: "拍摄工单处理照片，需要申请您的相机权限",
      photomsg: "从相册选取工单处理照片，需要申请您的相册权限",
    );
  }

  OnLocationResultListener? locationListener;

  List<BaiduLocation> locationList = [];

  @override
  void onCreated() {
    super.onCreated();
    locationListener = (location) {
      locationCount++;
      locationList.add(location);
      if(!location.city.isNullOrEmpty()){
        locationAddress = (location.address ?? "").replaceAll("中国", "");
        longitude = location.longitude;
        latitude = location.latitude;

        notifyListeners();
        debugPrint("locationAddress:${location.address}");
      }


    };
    LocationConfig.instance.addListener(locationListener!);
    LocationConfig.instance.startLocation(context);

    requestSiteCombo();
  }

  @override
  void dispose() {
    locationList.clear();
    if (locationListener != null) {
      LocationConfig.instance.removeListener(locationListener!);
    }
    LocationConfig.instance.stop();
    super.dispose();
  }

  void showLocationRecord(){
    showModalBottomSheet(context: context, builder: (context){
      return Container(

        child: ListView.builder(itemBuilder: (context,index){
          var location = locationList[index];
          return ListTile(
            title: Text("${index+1}.${location.address.toString()}（${location.errorCode}）"),
          );
        },itemCount: locationList.length,),
      );
    });
  }
}
